package com.example.cinemasystemv2.service;

import com.example.cinemasystemv2.entity.SystemLog;
import com.example.cinemasystemv2.repository.SystemLogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class SystemLogService {
    
    @Autowired
    private SystemLogRepository systemLogRepository;
    
    public List<SystemLog> getAllLogs() {
        return systemLogRepository.findAllOrderByTimeDesc();
    }
    
    public List<SystemLog> getLogsByUsername(String username) {
        return systemLogRepository.findByUsername(username);
    }
    
    public List<SystemLog> getLogsByOperation(String operation) {
        return systemLogRepository.findByOperation(operation);
    }
    
    public List<SystemLog> getLogsByDate(LocalDateTime date) {
        return systemLogRepository.findByDate(date);
    }
    
    public List<SystemLog> getLogsByDate(String dateStr) {
        try {
            LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDateTime startOfDay = date.atStartOfDay();
            LocalDateTime endOfDay = date.plusDays(1).atStartOfDay(); // 下一天的开始时间
            return systemLogRepository.findByDateRange(startOfDay, endOfDay);
        } catch (Exception e) {
            return getAllLogs(); // 如果日期解析失败，返回所有日志
        }
    }
    
    public List<SystemLog> getLogsByDateRange(LocalDateTime startTime, LocalDateTime endTime) {
        return systemLogRepository.findByDateRange(startTime, endTime);
    }
    
    public List<SystemLog> searchLogs(String keyword) {
        return systemLogRepository.searchLogs(keyword);
    }
    
    public SystemLog saveLog(SystemLog log) {
        if (log.getLogTime() == null) {
            log.setLogTime(LocalDateTime.now());
        }
        return systemLogRepository.save(log);
    }
    
    public void log(String message) {
        SystemLog log = new SystemLog(message);
        saveLog(log);
    }
    
    public void log(String message, String username, String operation) {
        SystemLog log = new SystemLog(message, LocalDateTime.now(), username, operation);
        saveLog(log);
    }
    
    public long getLogCountByDate(LocalDateTime date) {
        return systemLogRepository.countByDate(date);
    }
    
    public void deleteOldLogs(LocalDateTime beforeDate) {
        List<SystemLog> oldLogs = systemLogRepository.findByDateRange(LocalDateTime.of(2000, 1, 1, 0, 0), beforeDate);
        systemLogRepository.deleteAll(oldLogs);
    }
}